package org.cncy;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * Hello world!
 */
public class Utils {


    public static String url = "https://172.16.50.231/cgi-bin/dynamic_parser.cgi";

    public static void main(String[] args) throws DocumentException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        String XML3001 = "<?xml version='1.0' encoding='UTF-8' ?><Request><OperID><TenantID>mdm</TenantID><ClientUID></ClientUID><FlowNum></FlowNum><Timezone>-1</Timezone><Result>-1</Result><ClientVersion>1.3.1</ClientVersion><ClientBuildNum>103001</ClientBuildNum></OperID><ClientIDInfo><UserName>9080P</UserName><UserPassword>R2gd15lZQyMHOb269hbOfA==</UserPassword><EMMClientId></EMMClientId></ClientIDInfo><MobileIDInfo><ClientOSType>1</ClientOSType><ClientOS>Android</ClientOS><ModelType>2</ModelType><Model>SM-N976N</Model><OSVersion>7.1.2</OSVersion><Jailed>1</Jailed><Imei></Imei><WifiMac></WifiMac><Imsi>460072243927247</Imsi><SN>f29352fce9e55de5</SN><ClientIP>172.16.43.15</ClientIP><SdID></SdID><SpecialTypeFlag>0</SpecialTypeFlag><SSAID></SSAID><OAID></OAID></MobileIDInfo></Request>";
        String Xmlbody3001 = "<?xml version='1.0' encoding='UTF-8' ?><Request><OperID><TenantID>mdm</TenantID><ClientUID></ClientUID><FlowNum></FlowNum><Timezone>-1</Timezone><Result>-1</Result><ClientVersion>1.3.1</ClientVersion><ClientBuildNum>103001</ClientBuildNum></OperID><ClientIDInfo><UserName>liwy</UserName><UserPassword>4V10ef0nw3yUi4e1IMwKwg==</UserPassword><EMMClientId></EMMClientId></ClientIDInfo><MobileIDInfo><ClientOSType>1</ClientOSType><ClientOS>Android</ClientOS><ModelType>2</ModelType><Model>SM-N976N</Model><OSVersion>7.1.2</OSVersion><Jailed>1</Jailed><Imei>351564228292733</Imei><WifiMac></WifiMac><Imsi>460072243927249</Imsi><SN>f29352fce9e55de5</SN><ClientIP>172.16.43.15</ClientIP><SdID></SdID><SpecialTypeFlag>0</SpecialTypeFlag><SSAID></SSAID><OAID></OAID></MobileIDInfo></Request>";
        String XmlBody3009 = "<?xml version='1.0' encoding='UTF-8' ?><Request><OperID><TenantID>mdm</TenantID>636a577dd5d32d796172c7fd1bc31bdd8ac9dfb2<ClientUID>63c2f40ff9140f6dc4eb872c8b907e2e118561a2</ClientUID><FlowNum></FlowNum><Timezone>-1</Timezone><Result>-1</Result><ClientVersion>2.0.1</ClientVersion><ClientBuildNum>200001</ClientBuildNum></OperID><ClientIDInfo><UserName>liwy</UserName></ClientIDInfo></Request>";
        String XmlBody1001 = "<?xml version='1.0' encoding='UTF-8' ?><Request><OperID><TenantID>mdm</TenantID><ClientUID>e1bd8a1af3a8e432000c61f9ae9eb89b326af460</ClientUID><FlowNum>723353000</FlowNum><Timezone>-1</Timezone><Result>-1</Result><ClientVersion>2.0.1</ClientVersion><ClientBuildNum>200001</ClientBuildNum></OperID><AppInfo><ClientOS>1</ClientOS><Class>0</Class><OSVersion>12</OSVersion><CateId>0</CateId><StartIdx>0</StartIdx><RowNum>500</RowNum></AppInfo></Request>";
        String XmlBody5001 = "{\"header\":{\"version\":\"v2\"},\"body\":{\"maxCmdNum\":0,\"udid\":\"6d005190b72f391fa40712d58338b63cae345624\"}}";

        byte[] bytes1001 = HttpsXMLUtil.getXMLRequestByte(3001, XML3001);
        //byte[] bytes3009 = HttpsXMLUtil.getXMLRequestByte(3009, XmlBody3009);
        // byte[] xmlRequestByte = HttpsXMLUtil.getXMLRequestByte(1001, XmlBody1001);
        //byte[] bytes5001 = HttpsJsonUtil.getJsonRequestByte(5001, XmlBody5001);


       /* byte[] bytes = HttpsUtils.doPost(url, bytes1001);
        System.out.println(new String(bytes));*/
        // System.out.println(OkhttpUtil.builder().url(url).post().body(bytes1001).execute());

   /*     OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(new File("test.csv")));
        String num = "TEST";
        for (int i = 0; i < 100000; i++) {
            if (i < 10) {
                num += "00000" + i;
            } else if (i < 100) {
                num += "0000" + i;
            } else if (i < 1000) {
                num += "000" + i;
            } else if (i < 10000) {
                num += "00" + i;
            } else if (i < 100000) {
                num += "0" + i;
            }
            osw.write(num+"\n");
          osw.flush();
            num = "TEST";
        }*/
     /*

        System.out.println(new String(bytes,"utf-8"));*/


        byte[] bytes1 = interceptBody(bytes1001);
        System.err.println(new String(bytes1));
        // System.out.println(getRandom1(9));
    }


    public static String getRandom1(int len) {
        int rs = (int) ((Math.random() * 9 + 1) * Math.pow(10, len - 1));
        return String.valueOf(rs);
    }

    public static String findResult(byte[] doc, String elementName) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(new ByteArrayInputStream(doc));
        Element rootElement = read.getRootElement();
        Element element = rootElement.element("OperID").element(elementName);
        return element.getText();
    }

    /**
     * 截取加密部分
     *
     * @param bytes 含有加密头的报文
     * @return destBytes 返回正常报文
     */
    public static byte[] interceptBody(byte[] bytes) {
        if (null == bytes || bytes.length < 20) {
            throw new RuntimeException("报文异常");
        }
        byte[] destBytes = new byte[bytes.length - 20];
        System.arraycopy(bytes, 20, destBytes, 0, bytes.length - 20);
        return destBytes;
    }

    /**
     * @param httpUrl 发送请求的 URL
     * @param param   请求参数应该是{"key":"value"}的形式。
     * @return 所代表远程资源的响应结果
     * @deprecated 向指定 URL 发送POST方法的请求  使用https ip时 证书校验不可用，请使用httpsUtils中的方法
     */
    public static byte[] doPost(String httpUrl, byte[] param) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;


        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("PUT");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(Integer.MAX_VALUE);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/json");
            // 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            connection.setRequestProperty("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJyb2xlIjoiMTAiLCJ1c2VyX2lkIjoiYWRtaW4iLCJuYW1lIjoiYWRtaW4iLCJ0ZW5hbnRJZCI6Im1kbSIsImZ1bGxuYW1lIjoiQWRtaW5pc3RyYXRvciIsImV4cCI6MTcwMjM5OTgxNCwiYXVkIjoiVUVNIiwiaXNzIjoiaHR0cHM6Ly9iYWNrZW5kLm5hdGlvbnNreS5jb20ifQ.krSQ7BA1645tXFwdQR3iRShsmBD2eAr5hrENq01_PdooTarSeH_NMtiQyX1nB-64Gm-7gDdVDiWB2WUFUposPw");
            // 通过连接对象获取一个输出流

            // TODO: 2023/6/12 打印请求
            String strParam = new String(param, "utf-8");
            // System.out.println(strParam);

            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(param);
            // 通过连接对象获取一个输入流，向远程读取
            // if (connection.getResponseCode() == 200) {
            is = connection.getInputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            baos.close();

            /*    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    //sbf.append("\r\n");
                }
                result = sbf.toString();*/
            // }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return baos.toByteArray();
    }

    public static String whoAmI(Object o) {
        StringBuilder sb = new StringBuilder();
        sb.append(o.getClass().getSimpleName());
        sb.append(Thread.currentThread().toString());
        sb.append("@");
        sb.append(Integer.toHexString(o.hashCode()));
        // System.out.println("whoAmI = " + sb);
        return sb.toString();
    }

    public static String getRandomStr() {

        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
        StringBuilder randomString = new StringBuilder();
        SecureRandom secureRandom = new SecureRandom();
        for (int i = 0; i < 3; i++) {
            int randomIndex = secureRandom.nextInt(characters.length());
            randomString.append(characters.charAt(randomIndex));
        }
        String pre = randomString.toString();
        randomString.delete(0, pre.length());
        pre += "-";
        for (int i = 0; i < 4; i++) {
            int randomIndex = secureRandom.nextInt(characters.length());
            randomString.append(characters.charAt(randomIndex));
        }

        return pre + randomString.toString();
    }

    public static StringBuilder getRandomStrMin(int len) {
        String characters = "abcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder randomString = new StringBuilder();
        SecureRandom secureRandom = new SecureRandom();
        for (int i = 0; i < len; i++) {
            int randomIndex = secureRandom.nextInt(characters.length());
            randomString.append(characters.charAt(randomIndex));
        }
        return randomString;
    }
}
